package com.zjut.an.admin.dao;

import java.sql.Timestamp;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.zjut.an.news.dao.AnNews;
import com.zjut.an.role.dao.AnRole;
import com.zjut.an.util.module.PageModule;

/**
 * A data access object (DAO) providing persistence and search support for
 * AnAdmin entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.zjut.an.admin.dao.AnAdmin
 * @author MyEclipse Persistence Tools
 */

public class AnAdminDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory.getLogger(AnAdminDAO.class);
	// property constants
	public static final String AD_ID = "adId";
	public static final String RO_ID = "roId";
	public static final String ACCOUNT = "account";
	public static final String PASSWORD = "password";
	public static final String TRUENAME = "truename";
	public static final String PHONE = "phone";
	public static final String MOBILE = "mobile";
	public static final String EMAIL = "email";
	public static final String ACTIVE = "active";
	public static final String WC_IDS = "wcIds";

	protected void initDao() {
		// do nothing
	}

	public void sort(Criteria criteria, String sort, String order) {
		if (sort!=null && order!=null) {
			if (order.equals("asc")) {
				criteria.addOrder(Order.asc(sort));
			} else {
				criteria.addOrder(Order.desc(sort));
			}
		} else {
			criteria.addOrder(Order.desc(AD_ID));
		}
	}
	
	public void save(AnAdmin transientInstance) {
		log.debug("saving AnAdmin instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	
	public void update(AnAdmin transientInstance) {
		log.debug("updating AnAdmin instance");
		try {
			getHibernateTemplate().update(transientInstance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}

	public void delete(AnAdmin persistentInstance) {
		log.debug("deleting AnAdmin instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public AnAdmin findById(java.lang.Integer id) {
		log.debug("getting AnAdmin instance with id: " + id);
		try {
			AnAdmin instance = (AnAdmin) getHibernateTemplate().get(
					"com.zjut.an.admin.dao.AnAdmin", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(AnAdmin instance) {
		log.debug("finding AnAdmin instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding AnAdmin instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from AnAdmin as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByRoId(Object roId) {
		return findByProperty(RO_ID, roId);
	}

	public List findByAccount(Object account) {
		return findByProperty(ACCOUNT, account);
	}

	public List findByPassword(Object password) {
		return findByProperty(PASSWORD, password);
	}

	public List findByTruename(Object truename) {
		return findByProperty(TRUENAME, truename);
	}

	public List findByCall(Object call) {
		return findByProperty(PHONE, call);
	}

	public List findByEmail(Object email) {
		return findByProperty(EMAIL, email);
	}

	public List findByActive(Object active) {
		return findByProperty(ACTIVE, active);
	}
	
	public List findByWcIds(Object wcIds) {
		return findByProperty(WC_IDS, wcIds);
	}

	public List findAll() {
		log.debug("finding all AnAdmin instances");
		try {
			String queryString = "from AnAdmin";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public PageModule findByInstance(final int pageNumber ,final int pageSize, String sort, String order, final AnAdmin obj){
		try {
			int startIndex = (pageNumber - 1) * pageSize;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			List list;
			Criteria criteria = session.createCriteria(AnAdmin.class);
			
			if (!isEmpty(obj.getAccount())) {
				criteria.add(Restrictions.eq(ACCOUNT, obj.getAccount()));
			}
			if (!isEmpty(obj.getPassword())) {
				criteria.add(Restrictions.eq(PASSWORD, obj.getPassword()));
			}
			if (!isEmpty(obj.getActive())) {
				criteria.add(Restrictions.like(ACTIVE, obj.getActive(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getTruename())) {
				criteria.add(Restrictions.like(TRUENAME, obj.getTruename(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getPhone())) {
				criteria.add(Restrictions.like(PHONE, obj.getPhone(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getMobile())) {
				criteria.add(Restrictions.eq(MOBILE, obj.getMobile()));
			}
			if (null != obj.getRoId()) {
				criteria.add(Restrictions.eq(RO_ID, obj.getRoId()));
			}
			
			this.sort(criteria, sort, order);
			
			criteria.setFirstResult(startIndex);
			criteria.setMaxResults(pageSize);
			list = criteria.list();
			session.close();
			return new PageModule(pageNumber, pageSize, countByInstance(obj), list);
		} catch (RuntimeException re) {
			log.error("findByInstance failed", re);
			throw re;
		}
	}
	
	public int countByInstance(final AnAdmin obj) {
		log.debug("finding the number of AnAdmin instance");
		try {
			int count = 0;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			Criteria criteria = session.createCriteria(AnAdmin.class);

			if (!isEmpty(obj.getAccount())) {
				criteria.add(Restrictions.like(ACCOUNT, obj.getAccount(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getPassword())) {
				criteria.add(Restrictions.eq(PASSWORD, obj.getPassword()));
			}
			if (!isEmpty(obj.getActive())) {
				criteria.add(Restrictions.like(ACTIVE, obj.getActive(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getTruename())) {
				criteria.add(Restrictions.like(TRUENAME, obj.getTruename(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getPhone())) {
				criteria.add(Restrictions.like(PHONE, obj.getPhone(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getMobile())) {
				criteria.add(Restrictions.eq(MOBILE, obj.getMobile()));
			}
			if (null != obj.getRoId()) {
				criteria.add(Restrictions.eq(RO_ID, obj.getRoId()));
			}
			
			count = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
			session.close();
			return count;
		} catch (RuntimeException re) {
			log.error("find the number of AnAdmin instance failed", re);
			throw re;
		}
	}
	
	private boolean isEmpty(String value) {
		if (value==null || value.trim().length()==0) {
			return true;
		}
		return false;
	}
	
	public AnAdmin merge(AnAdmin detachedInstance) {
		log.debug("merging AnAdmin instance");
		try {
			AnAdmin result = (AnAdmin) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(AnAdmin instance) {
		log.debug("attaching dirty AnAdmin instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(AnAdmin instance) {
		log.debug("attaching clean AnAdmin instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static AnAdminDAO getFromApplicationContext(ApplicationContext ctx) {
		return (AnAdminDAO) ctx.getBean("AnAdminDAO");
	}
}